package com.chen.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.chen.model.entity.system.SysUser;
import com.chen.model.vo.common.Result;
import com.chen.model.vo.common.ResultCodeEnum;
import com.chen.util.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Struct;
import java.util.concurrent.TimeUnit;

/**
 * @author cgj
 * @date 2/10/25 9:02 AM
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     *执行controller前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String servletPath = request.getServletPath();
//        System.out.println("servletPath = " + servletPath);
//        请求方式为预检请求直接放行
        String method = request.getMethod();
        if(method.equalsIgnoreCase("options")){
            return  true;
        }
//        判断是否有token
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)) {
            responseNoLoginInfo(response);
            return  false;
        }
        String sysUser = redisTemplate.opsForValue().get("user:login:" + token);
        if(StrUtil.isEmpty(sysUser)){
            responseNoLoginInfo(response);
            return false;
        }
        SysUser sysuser = JSON.parseObject(sysUser, SysUser.class);
        AuthContextUtil.set(sysuser);
//        续命
        redisTemplate.expire("user:login:" + token,30, TimeUnit.MINUTES);
        return  true;
    }

    private void responseNoLoginInfo(HttpServletResponse response) {
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        response.setCharacterEncoding("utf-8");
        response.setContentType("test/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
//            响应给前端
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.close();
        }
    }


    /**
     * 响应前执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
